package me.numark.fragments;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import butterknife.Bind;
import butterknife.ButterKnife;
import me.numark.MainActivity;
import me.numark.R;
import me.numark.net.BaseResponse;
import me.numark.utils.Constants;
import me.numark.utils.Global;
import me.numark.utils.Utils;


public class BaseFragment extends Fragment {

    private static final String LOG_TAG = BaseFragment.class.getSimpleName();
    protected boolean needLogin = false;


    @Bind(R.id.toolbar)
    @Nullable
    Toolbar toolbar;

    @Bind(R.id.toolbar_title)
    @Nullable
    TextView titleTextView;

    @Bind(R.id.back)
    @Nullable
    View backInToolbar;

    View rootView;

    public BaseFragment() {
        // Required empty public constructor
    }

    BroadcastReceiver mBaseFragmentReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (Constants.ACTION_USER_CHANGED.equals(intent.getAction())) {
                refresh();
            }
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LocalBroadcastManager.getInstance(getActivity()).registerReceiver(mBaseFragmentReceiver,
                new IntentFilter(Constants.ACTION_USER_CHANGED));
    }

    @Override
    public void onDestroy() {
        LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(mBaseFragmentReceiver);
        super.onDestroy();

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_base, container, false);
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        rootView = view;
        ButterKnife.bind(this, view);
        if (getParentFragment() != null) {
            toolbar.setVisibility(View.GONE);
        } else {
            if (getActivity() instanceof MainActivity) {
                backInToolbar.setVisibility(View.INVISIBLE);
            } else {
                backInToolbar.setVisibility(View.VISIBLE);
                backInToolbar.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        getActivity().finish();
                    }
                });
            }
        }
        initUI(view);
        loadFromCache();
        refresh();
    }

    protected void initUI(View view) {

    }

    protected String cacheKey() {
        return null;
    }

    protected String getCacheName() {
        String cacheKey = cacheKey();
        if (TextUtils.isEmpty(cacheKey))
            return null;
        int uid = 0;
        if (Global.currentUser != null)
            uid = Global.currentUser.uid;
        return uid + "_" + cacheKey;
    }

    protected void loadFromCache() {
        String fileName = getCacheName();
        if (TextUtils.isEmpty(fileName)) {
            return;
        }
        File file = new File(Global.cacheJsonDir, fileName);
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(file);
            BufferedInputStream bis = new BufferedInputStream(fis);
            String data = Utils.readStream(bis);
            BaseResponse resp = parseData(data);
            if (resp != null) {
                bindData(resp, false);
            }
        } catch (Exception e) {
        } finally {
            Utils.closeQuietly(fis);
        }
    }

    protected BaseResponse parseData(String data) {
        return null;
    }

    protected void bindData(BaseResponse response, boolean isNew) {
        if (isNew && response.ret) {
            String fileName = getCacheName();
            if (!TextUtils.isEmpty(fileName)) {
                File file = new File(Global.cacheJsonDir, fileName);
                FileOutputStream fos = null;
                try {
                    String data = Global.getGson().toJson(response);
                    byte[] bytes = data.getBytes();
                    fos = new FileOutputStream(file);
                    BufferedOutputStream bos = new BufferedOutputStream(fos);
                    bos.write(bytes);
                } catch (Exception e) {
                } finally {
                    Utils.closeQuietly(fos);
                }
            }
        }

    }

    public void refresh() {

    }

}
